﻿using UnityEngine;

namespace Room
{
    public class RoomUIManager : MonoBehaviour
    {
        //private GameObject cache = null;

        public Camera uiCamera;

        private static RoomUIManager _instance;
        public static RoomUIManager Instance
        {
            get
            {
                return _instance;
            }
        }
        public void Awake()
        {
            _instance = this;
        }


        public delegate void eventCharactorClickHandler(RoomCharactor charactor);

        /// <summary>
        /// 在一个新的角色加入到场景中时调用
        /// </summary>
        public event eventCharactorClickHandler onCharactorClickCallback;

        public Transform clickDownTramsform;

        public void Tick()
        {
            if(Input.GetMouseButtonDown(0))
            {
                if (!UICamera.Raycast(Input.mousePosition))
                {
                    clickDownTramsform = GetMouseDownTrasform();
                }
            }

            if (Input.GetMouseButtonUp(0))
            {
                
                if (!UICamera.Raycast(Input.mousePosition))
                {
                    Transform transform = GetMouseDownTrasform();
                    if(transform != null&& transform == clickDownTramsform)
                    {
                        var charactor = transform.GetComponent<RoomCharactor>();
                        if (charactor != null)
                        {
                            ClickCharactor(charactor);
                        }
                    }
                }
                clickDownTramsform = null;
            }
        }

        public Transform GetMouseDownTrasform()
        {
            Ray ray = CameraTool.Instance.sceneCamera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            var can = Physics.Raycast(ray, out hit, 100, (1 << LayerName.SceneActor) | (1<<LayerName.Default) );

            if (can)
            {
                return hit.transform;
            }

            //if(hits!=null && hits.Length>0)
            //{
            //    return hits[0].transform;
            //}
            return null;
        }
        public void ClickCharactor(string charactorId)
        {
            var charactor = RoomManager.currentRoom.charactorManager.GetCharactor(charactorId);
            ClickCharactor(charactor);
        }

        public void ClickCharactor(RoomCharactor charactor)
        {
            if(charactor == null)
            {
                Debug.LogError("charactor click null");
            }
            charactor.Click();
            if (onCharactorClickCallback != null)
            {
                onCharactorClickCallback(charactor);
            }
        }
    }
}
